#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    void NodeStack(stack<TreeNode*>& s1, TreeNode* root, TreeNode* f)
    {
        s1.push(root);
        cout << s1.top()->val << " ";

        if (root == f)
            return;
        if (root->val > f->val)
            NodeStack(s1, root->left, f);
        else
            NodeStack(s1, root->right, f);

        //s1.push(root);
        //cout << s1.top()->val << " ";
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> p1;
        stack<TreeNode*> q1;
        NodeStack(p1, root, p);
        cout << endl;
        NodeStack(q1, root, q);
        while (p1.size() != q1.size())
        {
            if (p1.size() > q1.size())
                p1.pop();
            else
                q1.pop();
        }
        //cout << p1.top()->val << " " << q1.top()->val << endl;

        while (p1.top() != q1.top())
        {
            p1.pop();
            q1.pop();
        }

        return p1.top();
    }
};